package main

import (
	"log"
	"os"

	"github.com/gin-gonic/gin"
	"license-service/internal/encryption"
	"license-service/internal/home"
	"license-service/internal/license"
)

func main() {
	// 设置为发布模式
	gin.SetMode(gin.ReleaseMode)
	r := gin.Default()

	// 设置路由
	setupRoutes(r)

	port := os.Getenv("PORT")
	if port == "" {
		port = "8080"
	}

	log.Printf("Starting Toolset server on port %s", port)
	log.Printf("Available tools: license, encryption")
	if err := r.Run(":" + port); err != nil {
		log.Fatalf("Failed to start server: %v", err)
	}
}

func setupRoutes(r *gin.Engine) {
	// 主页路由
	r.GET("/", home.HomePage)

	// 设置license工具路由
	setupLicenseRoutes(r)
	
	// 设置encryption工具路由
	setupEncryptionRoutes(r)
	
	// 可以在这里添加其他工具的路由
	// setupOtherToolRoutes(r)
}

func setupLicenseRoutes(r *gin.Engine) {
	// API路由组
	api := r.Group("/api/license")
	{
		// 生成License相关路由
		generate := api.Group("/generate")
		{
			generate.GET("", getHardwareInfo)
			generate.POST("", generateLicense)
		}
		
		// 状态检查路由
		api.GET("/status", verifyLicense)
	}
	
	// 页面路由
	r.GET("/license", license.LicensePage)
	r.GET("/license/batch", license.BatchLicensePage)
}

func setupEncryptionRoutes(r *gin.Engine) {
	// API路由组
	api := r.Group("/api/encryption")
	{
		api.POST("/encrypt", encryption.EncryptHandler)
		api.POST("/decrypt", encryption.DecryptHandler)
	}
	
	// 页面路由
	r.GET("/encryption", encryption.EncryptionPage)
}

// getHardwareInfo 获取硬件信息
func getHardwareInfo(c *gin.Context) {
	info, err := license.GetHardwareInfo()
	if err != nil {
		c.JSON(500, gin.H{
			"status":  500,
			"message": "服务器内部错误",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"status":  200,
		"message": "硬件信息获取成功",
		"data": map[string]interface{}{
			"cpuId":      info.CPUID,
			"cpuName":    info.CPUName,
			"macAddress": info.MacAddress,
			"timestamp":  info.Timestamp,
		},
	})
}

// generateLicense 生成License
func generateLicense(c *gin.Context) {
	var req struct {
		CPUID      string `json:"cpuId" binding:"required"`
		CPUName    string `json:"cpuName" binding:"required"`
		MacAddress string `json:"macAddress" binding:"required"`
		PublicIP   string `json:"publicIp"`
		ExpiryDate string `json:"expiryDate" binding:"required"`
		Admin      bool   `json:"admin"`
	}

	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(400, gin.H{
			"status":  400,
			"message": "参数验证失败: " + err.Error(),
		})
		return
	}

	// 生成硬件指纹
	hardwareHash := license.GenerateHardwareHash(req.CPUID, req.CPUName, req.MacAddress, req.PublicIP)

	// 生成License
	lic, err := license.GenerateLicense(hardwareHash, req.ExpiryDate, req.Admin)
	if err != nil {
		c.JSON(500, gin.H{
			"status":  500,
			"message": "读取私钥或签名失败，请确保私钥文件存在",
			"error":   err.Error(),
		})
		return
	}

	c.JSON(200, gin.H{
		"status":  200,
		"message": "License生成成功",
		"data":    lic,
	})
}

// verifyLicense 验证License
func verifyLicense(c *gin.Context) {
	status, err := license.VerifyLicense()
	if err != nil {
		c.JSON(500, gin.H{
			"status":  500,
			"message": "验证过程中发生错误",
			"error":   err.Error(),
		})
		return
	}

	statusCode := 200
	if !status.Valid {
		statusCode = 403
	}

	c.JSON(statusCode, gin.H{
		"status":  statusCode,
		"message": status.Reason,
		"data":    status,
	})
}